<template>
    <div class="app-container">
        <!-- 搜索工作栏 -->
        <el-form
            :model="queryParams"
            ref="queryForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
            <el-row>
                <el-form-item label="链接" prop="linkUrl">
                    <el-input
                        v-model="queryParams.linkUrl"
                        placeholder="请输入链接URL"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="工单ID" prop="workId">
                    <el-input
                        v-model="queryParams.workId"
                        placeholder="请输入工单ID"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="工单名称" prop="workName">
                    <el-input
                        v-model="queryParams.workName"
                        placeholder="请输入工单名称"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="号码" prop="accountNumber">
                    <el-input
                        v-model="queryParams.accountNumber"
                        placeholder="请输入号码"
                        clearable
                        @keyup.enter.native="handleQuery"
                    />
                </el-form-item>
                <el-form-item label="类型" prop="numberType">
                    <el-select
                        v-model="queryParams.numberType"
                        placeholder="请选择号码类型"
                        clearable
                        @keyup.enter.native="handleQuery"
                    >
                        <el-option
                            :label="item.label"
                            :value="item.value"
                            v-for="item in numberTypeList"
                            :key="item.value"
                        ></el-option>
                    </el-select>
                </el-form-item>
            </el-row>
            <el-row>
                <el-form-item label="状态" prop="status">
                    <el-select
                        v-model="queryParams.status"
                        placeholder="请选择状态"
                        clearable
                        @keyup.enter.native="handleQuery"
                    >
                        <el-option :label="'正常'" :value="1"></el-option>
                        <el-option :label="'停用'" :value="0"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item
                    label="操作人"
                    prop="userId"
                    v-if="
                        roles.includes('super_admin') || roles.includes('admin')
                    "
                >
                    <el-select
                        v-model="queryParams.userId"
                        placeholder="请选操作人"
                        clearable
                        filterable
                        @keyup.enter.native="handleQuery"
                    >
                        <el-option
                            :label="item.nickname"
                            :value="item.id"
                            v-for="(item, i) in userList"
                            :key="i"
                        ></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item>
                    <el-button
                        type="primary"
                        icon="el-icon-search"
                        @click="handleQuery"
                        >搜索</el-button
                    >
                    <el-button icon="el-icon-refresh" @click="resetQuery"
                        >重置</el-button
                    >
                </el-form-item>
            </el-row>
        </el-form>
        <el-row :gutter="10" class="mb8">
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    @click="openForm({})"
                    >新增</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    plain
                    size="mini"
                    @click="patchDel"
                    type="danger"
                    icon="el-icon-delete"
                    >批量删除</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    plain
                    size="mini"
                    type="primary"
                    icon="el-icon-edit"
                    @click="updateStatus"
                    >批量更新状态</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    plain
                    size="mini"
                    type="primary"
                    icon="el-icon-download"
                    @click="downloadNumber(1)"
                    >批量强制下号</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    plain
                    size="mini"
                    type="primary"
                    icon="el-icon-download"
                    @click="downloadNumber(0)"
                    >批量取消强制下号</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="warning"
                    plain
                    icon="el-icon-download"
                    size="mini"
                    @click="handleExport"
                    :loading="exportLoading"
                    v-hasPermi="['tk:account-numbers:export']"
                    >导出</el-button
                >
            </el-col>
            <!-- <el-col :span="1.5">
                <el-button type="primary" plain size="mini"
                    >本页访间次数合计:1440</el-button
                >
            </el-col> -->
        </el-row>
        <el-table
            v-loading="loading"
            :data="list"
            :stripe="true"
            :show-overflow-tooltip="true"
            border
            size="mini"
            max-height="680"
            @selection-change="handleSelectionChange"
        >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column
                label="号码ID"
                prop="id"
                width="120"
                align="center"
            />
            <el-table-column label="链接URL" prop="linkName" align="center">
                <template slot-scope="scope">
                    <el-tag
                        size="mini"
                        @click="copyText(scope.row)"
                        class="lk-p"
                        >{{ scope.row.linkName }}</el-tag
                    >
                </template>
            </el-table-column>
            <el-table-column label="域名" prop="domain" align="center" />

            <el-table-column label="工单名称" prop="workName" align="center" />
            <el-table-column
                label="号码"
                prop="accountNumber"
                align="center"
            ></el-table-column>
            <el-table-column label="号码类型" prop="numberType" align="center">
                <template v-slot="scope">
                    <span>{{
                        {
                            1: "WhatsApp",
                            2: "Telegram",
                            3: "Line",
                            4: "自定义",
                        }[scope.row.numberType || 1]
                    }}</span>
                </template>
            </el-table-column>
            <el-table-column
                label="访问次数"
                prop="visits"
                align="center"
            ></el-table-column>
            <el-table-column
                label="进线人数"
                prop="inboundCount"
                align="center"
            >
                <template #default="scope">
                    {{
                        String(scope.row.inboundCount) === "null"
                            ? "--"
                            : scope.row.inboundCount
                    }}
                </template>
            </el-table-column>
            <el-table-column
                label="操作人"
                prop="nickname"
                align="center"
            ></el-table-column>
            <el-table-column
                label="强制下号"
                prop="compulsoryDown"
                align="center"
            >
                <template v-slot="scope">
                    <el-switch
                        v-model="scope.row.compulsoryDown"
                        :active-value="1"
                        :inactive-value="0"
                        @change="handleCompulsoryDownChange(scope.row)"
                    />
                </template>
            </el-table-column>

            <el-table-column label="状态" prop="status" align="center">
                <template v-slot="scope">
                    <el-switch
                        v-model="scope.row.status"
                        :active-value="1"
                        :inactive-value="0"
                        :disabled="scope.row.compulsoryDown == 1"
                        @change="handleStatusChange(scope.row)"
                    />
                </template>
            </el-table-column>

            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
            >
                <template v-slot="scope">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        @click="openForm(scope.row)"
                        v-hasPermi="['tk:account-numbers:update']"
                        >修改</el-button
                    >

                    <!-- v-hasPermi="['tk:links:delete']" -->
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        @click="handleDelete(scope.row)"
                        v-hasPermi="['tk:account-numbers:delete']"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <pagination
            v-show="total > 0"
            :total="total"
            :page.sync="queryParams.pageNo"
            :limit.sync="queryParams.pageSize"
            @pagination="getList"
        />
        <AForm ref="formRef" @success="getList" />
        <!-- ...........批量修改状态弹窗............ -->
        <el-dialog title="提示" :visible.sync="dialogVisible" width="300px">
            <div>
                <el-radio-group v-model="switchValue">
                    <el-radio :label="1">开启</el-radio>
                    <el-radio :label="0">关闭</el-radio>
                </el-radio-group>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button @click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="updataNoStatus"
                    >确 定</el-button
                >
            </span>
        </el-dialog>
    </div>
</template>
<script>
import {
    getNoList,
    updataNoStatus,
    deleteNo,
    exportNo,
    editNo,
    downloadNo,
} from "@/api/No";
import AForm from "./aForm.vue";
import router from "@/router/index";
import { Loading } from "element-ui";
import copy from "copy-to-clipboard";
import { listUser } from "@/api/system/user";
import store from "@/store";

export default {
    components: {
        AForm,
    },
    data() {
        return {
            // 遮罩层
            loading: true,
            exportLoading: false,
            // 表格数据
            list: [],
            roles: store.getters.roles,
            numberTypeList: [
                // 1：WhatsApp，2：Telegram，3：Line，4：自定义
                {
                    label: "WhatsApp",
                    value: 1,
                },
                {
                    label: "Telegram",
                    value: 2,
                },
                {
                    label: "Line",
                    value: 3,
                },
                {
                    label: "自定义",
                    value: 4,
                },
            ],
            total: 0,
            // 显示搜索条件
            showSearch: true,
            dialogVisible: false,
            switchValue: 1,
            userList: [],
            queryParams: {
                pageNo: 1,
                pageSize: 10,
            },
            ids: [],
        };
    },
    methods: {
        // 复制文本方法
        async copyText(row) {
            const url = "https://" + row.domain + "/?url=" + row.linkName;
            try {
                await copy(url);
                this.$message.success("复制成功");
            } catch (err) {
                this.$message.error("复制失败");
            }
        },

        hasSelectdIds() {
            if (this.ids.length === 0) {
                this.$message.info("请选择要操作的项");
            }
            return this.ids.length > 0;
        },
        updateStatus() {
            const hasIds = this.hasSelectdIds();
            if (hasIds) {
                this.dialogVisible = true;
            }
        },
        async getList() {
            this.loading = true;
            const { code, data } = await getNoList(this.queryParams);
            if (code === 0) {
                this.list = data?.list || [];
                this.total = data?.total || 0;
            }

            this.loading = false;
        },
        /** 搜索按钮操作 */
        handleQuery() {
            this.queryParams.pageNo = 1;
            this.getList();
        },
        /** 重置按钮操作 */
        resetQuery() {
            this.resetForm("queryForm");
            this.handleQuery();
        },
        /** 添加/修改操作 */
        openForm(row) {
            this.$refs["formRef"].open(row);
        },
        /** 删除按钮操作 */
        async handleDelete(row) {
            const id = row.id;
            await this.$modal
                .confirm(
                    '是否确认删链接号码为"' + row.accountNumber + '"的数据项?'
                )
                .then(async () => {
                    try {
                        const res = await deleteNo({
                            ids: id,
                        });
                        if (res.code === 0) {
                            await this.getList();
                            this.$modal.msgSuccess("删除成功");
                        } else {
                            this.$modal.msgError(res.msg);
                        }
                    } catch {}
                })
                .catch(() => {});
        },

        /** 导出按钮操作 */
        async handleExport() {
            await this.$modal.confirm("是否确认导出所有号码数据项?");
            let downloadLoadingInstance;
            try {
                this.exportLoading = true;
                downloadLoadingInstance = Loading.service({
                    text: "正在导出数据，请稍候",
                    spinner: "el-icon-loading",
                    background: "rgba(0, 0, 0, 0.7)",
                });
                const res = await exportNo(this.queryParams);
                let routerName = router.app._route.meta.title;
                let fileName = "号码-";
                if (routerName) {
                    fileName = routerName + "-";
                }
                this.$download.excel(
                    res,
                    fileName +
                        this.parseTime(new Date(), "{y}{m}{d}{h}{i}{s}") +
                        ".xls"
                );
            } finally {
                this.exportLoading = false;
                downloadLoadingInstance.close();
            }
        },
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item.id);
        },
        async pathDelete() {
            const { code, msg } = await deleteNo({
                ids: this.ids.join(","),
            });
            if (code === 0) {
                this.$modal.msgSuccess("删除成功");
                this.getList();
            } else {
                this.$modal.msgError(msg);
            }
        },
        async downloadNumber(val) {
            this.ids.forEach((id, i) => {
                downloadNo({
                    id: id,
                    compulsoryDown: val,
                });
                if (i === this.ids.length - 1) {
                    this.getList();
                    this.$modal.msgSuccess(val ? "下号成功" : "取消下号成功");
                }
            });
        },
        async updataNoStatus() {
            const { code, msg } = await updataNoStatus({
                ids: this.ids.join(","),
                status: this.switchValue,
            });
            if (code === 0) {
                this.$modal.msgSuccess("状态已更新");
                this.dialogVisible = false;
                this.switchValue = 1;
                this.getList();
            } else {
                this.$modal.msgError(msg);
            }
        },
        async handleStatusChange(row) {
            if (row.compulsoryDown === 1) return;
            const res = await updataNoStatus({
                status: row.status,
                ids: row.id,
            });
            if (res.code === 0) {
                this.$modal.msgSuccess("状态更新成功");
            }
        },
        async handleCompulsoryDownChange(row) {
            const res = await editNo({
                compulsoryDown: row.compulsoryDown,
                id: row.id,
            });
            if (res.code === 0) {
                this.$modal.msgSuccess(
                    row.compulsoryDown ? "已强制下号" : "已解除下号！"
                );
            }
        },

        patchDel() {
            const hasIds = this.hasSelectdIds();
            if (hasIds) {
                this.$confirm("请确认是否删除选中号码?", "提示", {
                    confirmButtonText: "确定",
                    cancelButtonText: "取消",
                    type: "warning",
                })
                    .then(() => {
                        this.pathDelete();
                    })
                    .catch(() => {
                        this.$message({
                            type: "info",
                            message: "已取消删除",
                        });
                    });
            }
        },

        async getUserList(val) {
            const { code, data } = await listUser(val);
            if (code === 0) {
                this.userList = data.list;
            }
        },
    },
    created() {
        this.getList();
        if (
            store.getters.roles &&
            (store.getters.roles.includes("super_admin") ||
                store.getters.roles.includes("admin"))
        ) {
            this.getUserList({
                pageNo: 1,
                pageSize: 3000,
            });
        }
    },
};
</script>
